import { defineStore } from 'pinia'
import $axios from '../utils/axios'
import { ElMessage } from 'element-plus'

export const useServiceorderStore = defineStore('serviceorder', {
    state: () => {
        return {
            index: -1,
            currentPage: 1,
            pageSize: 8,
            total: '',
            background: true,
            dialogFormVisible: false,
            tableData: [],
            formData: {},
            updateFrom: {
            },
            myOrder: [],
            noAcceptData: [],
            noFinishData: [],
            noReviewData: [],
        }
    },
    actions: {
        async init() {//ServiceOrder
            const path = '/serviceOrder/selectAllByPage/' + this.currentPage + '/' + this.pageSize
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.tableData = res.result.map(item => ({
                    ...item,
                    orderState: Number(item.orderState)
                }))
                this.total = parseInt(res.msg)
                console.log('订单数据:', this.tableData);
            }
        },
        async initHealth() {//HealthOrder
            try {
                const path = '/serviceOrder/selectHealthByPage/' + this.currentPage + '/' + this.pageSize
                console.log('请求路径:', path)
                const { data: res } = await $axios.get(path)
                if (res.code === 200) {
                    // 确保orderState是数字类型
                    this.tableData = res.result.map(item => ({
                        ...item,
                        orderState: Number(item.orderState)
                    }))
                    this.total = parseInt(res.msg)
                    console.log('健康订单数据:', this.tableData)
                } else {
                    console.error('获取健康订单数据失败:', res)
                    ElMessage.error(res.msg || '获取数据失败')
                }
            } catch (error) {
                console.error('获取健康订单数据出错:', error)
                if (error.response) {
                    // 服务器响应了，但状态码不在 2xx 范围内
                    console.error('响应状态:', error.response.status)
                    console.error('响应数据:', error.response.data)
                    ElMessage.error(`请求失败 (${error.response.status}): ${error.response.data.msg || '未知错误'}`)
                } else if (error.request) {
                    // 请求已发出，但没有收到响应
                    console.error('未收到响应')
                    ElMessage.error('服务器无响应，请检查网络连接')
                } else {
                    // 请求配置出错
                    console.error('请求配置错误:', error.message)
                    ElMessage.error('请求配置错误: ' + error.message)
                }
            }
        },
        preInfo4ServiceEdit(index, row) {
            try {
                console.group('处理服务订单编辑')
                this.index = index
                this.updateFrom.id = row.id

                // 从localStorage获取用户信息
                const user = JSON.parse(localStorage.getItem("user"))
                if (!user) {
                    console.error('用户信息不存在')
                    ElMessage.error('请重新登录')
                    return
                }

                console.log('用户信息:', user)
                this.updateFrom.mId = user.id
                console.log('更新表单:', this.updateFrom)
                
                this.dialogFormVisible = true
                console.groupEnd()
            } catch (error) {
                console.error('处理订单编辑出错:', error)
                ElMessage.error('处理订单时出错')
                console.groupEnd()
            }
        },
        preInfo4HealthEdit(index, row) {
            try {
                console.group('处理健康订单编辑')
                this.index = index
                this.updateFrom.id = row.id

                // 从localStorage获取用户信息
                const user = JSON.parse(localStorage.getItem("user"))
                if (!user) {
                    console.error('用户信息不存在')
                    ElMessage.error('请重新登录')
                    return
                }

                console.log('用户信息:', user)
                this.updateFrom.dId = user.id
                console.log('更新表单:', this.updateFrom)
                
                this.dialogFormVisible = true
                console.groupEnd()
            } catch (error) {
                console.error('处理订单编辑出错:', error)
                ElMessage.error('处理订单时出错')
                console.groupEnd()
            }
        },
        async updateOrder() {
            try {
                var now = new Date()
                var year = now.getFullYear()
                var month = now.getMonth() + 1 < 10 ?
                    '0' + (now.getMonth() + 1) : now.getMonth() + 1
                var day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
                var hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours()
                var minute = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()
                var second = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds()
                var date = year + '-' + month + '-' + day
                var time = hour + ":" + minute + ":" + second
                
                // 验证必填字段
                if (!this.updateFrom.name || !this.updateFrom.telephone) {
                    ElMessage.error('请选择服务人员并填写联系电话')
                    return
                }

                // 验证电话号码格式
                const phoneReg = /^1[3-9]\d{9}$/
                if (!phoneReg.test(this.updateFrom.telephone)) {
                    ElMessage.error('服务人员电话号码格式不正确')
                    return
                }

                const updateData = {
                    ...this.updateFrom,
                    acceptDate: date,
                    acceptTime: time,
                    orderState: 2 // 直接设置为待完成状态
                }
                
                console.log('更新订单数据:', updateData)
                const path = '/serviceOrder/update'
                const { data: res } = await $axios.post(path, updateData)
                if (res.code === 200) {
                    this.dialogFormVisible = false
                    await this.init() // 重新加载数据
                    ElMessage({
                        message: '已受理!',
                        type: 'success',
                    })
                } else {
                    ElMessage.error(res.msg || '操作失败，请重试')
                }
            } catch (error) {
                console.error('更新订单出错:', error)
                ElMessage.error('操作失败：' + (error.response?.data?.msg || error.message || '未知错误'))
            }
        },
        submit() {
            // const
        },
        async loadByUid() {//我的全部订单
            const user = JSON.parse(sessionStorage.getItem("user"))
            const path = '/serviceOrder/selectByUId/' + user.id
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.myOrder = res.result
                console.log(this.myOrder);
            }
        },
        async getNoAccept() {//我的待受理订单
            const user = JSON.parse(sessionStorage.getItem("user"))
            const path = '/serviceOrder/selectByuIdByState/' + user.id + '/' + 0
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.noAcceptData = res.result
            }
        },
        async getNoFinish() {//我的未完成订单
            const user = JSON.parse(sessionStorage.getItem("user"))
            const path = '/serviceOrder/selectByuIdByState/' + user.id + '/' + 2
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.noFinishData = res.result
            }
        },
        async getNoReview() {//我的待评价订单
            const user = JSON.parse(sessionStorage.getItem("user"))
            const path = '/serviceOrder/selectByuIdByState/' + user.id + '/' + 3
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.noReviewData = res.result
            }
            // this.loadByUid()
            // console.log(this.myOrder);
            // let j = 0;
            // for (let i = 0; i < this.myOrder.length; i++) {
            //     if (this.myOrder[i].orderState === 2) {
            //         console.log(this.myOrder[i]);
            //         this.noReviewData[j++] = this.myOrder[i]
            //         console.log(this.noReviewData[j]);
            //     }
            // }
            // console.log(this.noReviewData);
        },
        updateDate() {
            var now = new Date()
            var year = now.getFullYear()
            var month = now.getMonth() + 1 < 10 ?
                '0' + (now.getMonth() + 1) : now.getMonth() + 1
            var day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
            var date = year + '-' + month + '-' + day
            return date;
        },
        updateTime() {
            var now = new Date()
            var hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours()
            var minute = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()
            var second = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds()
            var time = hour + ":" + minute + ":" + second
            return time;
        },
        async updateState(index, row) {
            this.updateFrom.id = row.id
            this.updateFrom.orderState = row.orderState + 1
            console.log(this.updateFrom)
            const path = '/serviceOrder/update'
            const { data: res } = await $axios.post(path, this.updateFrom)
            if (res.code === 200) {
                this.loadByUid()
                this.getNoAccept()
                this.getNoFinish()
                this.getNoReview()
            } else {
                ElMessage.error('Oops, this is a error message.')
            }

        },
        async addTestData() {
            const testOrders = [
                {
                    uId: 6, // lisisi 的用户ID
                    typeBId: 4,  // 医疗服务
                    typeSId: 15, // 常规体检
                    reserveDate: '2024-03-14',
                    serviceAddress: '北京市朝阳区社区医院',
                    orderDetail: '需要进行常规体检',
                    orderState: 0,
                    orderDate: this.updateDate(),
                    orderTime: this.updateTime()
                },
                {
                    uId: 6,
                    typeBId: 4,  // 医疗服务
                    typeSId: 16, // 康复理疗
                    reserveDate: '2024-03-15',
                    serviceAddress: '北京市海淀区社区医院',
                    orderDetail: '需要进行康复理疗',
                    orderState: 0,
                    orderDate: this.updateDate(),
                    orderTime: this.updateTime()
                },
                {
                    uId: 6,
                    typeBId: 4,  // 医疗服务
                    typeSId: 17, // 保健按摩
                    reserveDate: '2024-03-16',
                    serviceAddress: '北京市西城区社区医院',
                    orderDetail: '需要进行保健按摩',
                    orderState: 0,
                    orderDate: this.updateDate(),
                    orderTime: this.updateTime()
                }
            ];

            try {
                console.log('开始添加测试数据...');
                for (const order of testOrders) {
                    console.log('正在添加订单:', order);
                    const { data: res } = await $axios.put('/serviceOrder/insert', order);
                    console.log('服务器响应:', res);
                    if (res.code === 200) {
                        console.log('订单创建成功:', res.result);
                    } else {
                        console.error('订单创建失败:', res);
                        ElMessage.error('订单创建失败：' + res.msg);
                        return;
                    }
                }
                
                console.log('所有测试数据添加完成，开始刷新列表...');
                ElMessage.success('测试数据添加完成');
                await this.initHealth(); // 刷新列表
                console.log('列表刷新完成');
            } catch (error) {
                console.error('添加测试数据失败:', error);
                if (error.response) {
                    console.error('错误响应:', error.response);
                    ElMessage.error('添加失败：' + (error.response.data.msg || '服务器错误'));
                } else if (error.request) {
                    console.error('未收到响应:', error.request);
                    ElMessage.error('服务器无响应，请检查网络连接');
                } else {
                    console.error('请求错误:', error.message);
                    ElMessage.error('请求错误: ' + error.message);
                }
            }
        },
    }
})